package org.xiaov.lunasql.engine.transform;

import com.alibaba.druid.DbType;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import org.xiaov.lunasql.engine.common.loader.EnhancedServiceLoader;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * TransformManager
 * </p>
 *
 * @author LunaSQL
 * @since 2024/12/11 21:59
 */
public class TransformManager {

    private static final Map<DbType, Transform> transformMap = new HashMap<>();
    /**
     * 实例
     */
    public static final TransformManager INSTANCE = new TransformManager();

    static {
        List<Transform> allTransform = EnhancedServiceLoader.loadAll(Transform.class);
        allTransform.forEach(transform -> transformMap.put(transform.registerType(), transform));
    }

    /**
     * 构造函数
     */
    public TransformManager() {
    }

    /**
     * 解析sql
     *
     * @param sql    sql
     * @param dbType 目标数据库类型
     * @return 转换之后的sql
     */
    public String parseSQL(String sql, String dbType) {
        return parseSQL(sql, DbType.of(dbType));
    }

    /**
     * 解析sql
     *
     * @param sql    sql
     * @param dbType 目标数据库类型
     * @return 转换之后的sql
     */
    public String parseSQL(String sql, DbType dbType) {
        if (DbType.mysql == dbType) {
            //如果是mysql的话，不进行转换
            return sql;
        }
        //将sql解析成语法树
        List<SQLStatement> sqlStatementList = SQLUtils.parseStatements(sql, DbType.mysql);

        Transform transform = transformMap.get(dbType);
        if (transform == null) {
            throw new IllegalArgumentException("支持的数据库类型：" + dbType.name());
        }

        StringBuilder builder = new StringBuilder();
        for (SQLStatement sqlStatement : sqlStatementList) {
            sqlStatement.accept(transform.getAtsVisitorAdapter());
            builder.append(sqlStatement);
            builder.append("\n");
        }
        return SQLUtils.format(builder.toString(), dbType);
    }

}
